<template>
  <div class="page">
    <h1>Upload 组件的使用</h1>
    <AvatarUpload v-model="headImg" />

    <hr />

    <el-upload
      ref="uploadRef"
      list-type="picture"
      v-model:file-list="fileList"
      :headers="{
        Authorization:
          'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc1JlZnJlc2giOmZhbHNlLCJyb2xlSWRzIjpbMV0sInVzZXJuYW1lIjoiYWRtaW4iLCJ1c2VySWQiOjEsInBhc3N3b3JkVmVyc2lvbiI6NywiaWF0IjoxNzA2NzY2NzA4LCJleHAiOjE3MDY3NzM5MDh9.q5v3SW6-3ppcKSWidYHeFN3tHdNMZotFttYHbYyHal4',
      }"
      action="/api/admin/base/comm/upload"
      multiple
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :limit="4"
      :auto-upload="false"
      :on-exceed="handleExceed"
    >
      <el-button type="primary">Click to upload</el-button>
    </el-upload>

    <el-button type="success" @click="handleUpload">手动上传</el-button>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from "element-plus";
import { uploadAPI } from "@/api/sys.js";
import AvatarUpload from "@/components/avatar-upload/index.vue";

export default {
  name: "Test3",
  components: { AvatarUpload },

  data() {
    return {
      fileList: [], // 文件列表
      headImg:
        "http://127.0.0.1:8001/public/uploads/20240201/641cafc0-c0d6-11ee-884e-a71aa0e4d323.jpg",
    };
  },

  methods: {
    // 手动上传
    handleUpload() {
      // 一、调用 upload 组件提供的 submit 方法
      this.$refs.uploadRef.submit();
      // 二、调用自己的上传函数
      // uploadAPI({
      //   file: this.fileList[0].raw,
      // });
    },

    handleRemove(file, uploadFiles) {
      console.log("handleRemove", file, uploadFiles);
    },
    handlePreview(uploadFile) {
      console.log("handlePreview", uploadFile);
      //
    },
    // 超出限制时触发的函数
    //  files - 当前超出的文件列表
    handleExceed(files, uploadFiles) {
      // ElMessage.warning("超出限制");

      const file = files[0];
      console.log("file", file);
      // 清空文件列表
      this.$refs.uploadRef.clearFiles();

      // 手动选择当前文件
      this.$refs.uploadRef.handleStart(file);
    },
    beforeRemove(uploadFile, uploadFiles) {
      console.log("uploadFile", uploadFile);
      return ElMessageBox.confirm(
        `Cancel the transfer of ${uploadFile.name} ?`,
      ).then(
        () => true,
        () => false,
      );
    },
  },
};
</script>
